package com.humble.humbleojjudgeservice.judge.rabbit;

import com.humble.humbleojmodel.model.enums.RabbitTransportKey;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeoutException;

@Slf4j
@Component
public class MqInit {
    @Value("${spring.rabbitmq.host}")
    private String host;

    //該註解表示初始化bean完成后立即執行
    @PostConstruct
    public void doInit(){
        try {
             ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost(host);
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            String EXCHANGE_NAME= RabbitTransportKey.EXCHANGE_NAME.getValue();
            channel.exchangeDeclare(EXCHANGE_NAME,"direct");

            String QUEUE_NAME=RabbitTransportKey.QUEUE_NAME.getValue();
            channel.queueDeclare(QUEUE_NAME,true,false,false,null);
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,RabbitTransportKey.ROUTING_KEY.getValue());
            log.info("消息队列启动成功");
        } catch (Exception e) {
            log.error("消息队列启动失败");
            throw new RuntimeException(e);
        }
    }
}
